'use strict';

const {
	type
} = require("os");

let db = uniCloud.database();
exports.main = async (event, context) => {
	if (event.type == "changeAvatar") {
		const transaction = await db.startTransaction();
		try {
			const resIsHaveAvatar = await transaction.collection("roomcenteruser").doc(event.uid).get();
			if (!resIsHaveAvatar.data.avatar) {
				const resUpdateUser = await transaction.collection("roomcenteruser").doc(event.uid).update({
					avatar: event.fileID
				});
				if (resUpdateUser.updated) {
					await transaction.commit();
					return {
						success: true,
						avatarUrl: event.fileID
					}
				}
			} else {
				const resUpdateUser = await transaction.collection("roomcenteruser").doc(event.uid).update({
					avatar: event.fileID
				});
				const resDelAvatar = await uniCloud.deleteFile({
					fileList: [
						resIsHaveAvatar.data.avatar
					]
				});
				//return resDelAvatar;
				if (resUpdateUser.updated && resDelAvatar.fileList[0].fileID) {
					await transaction.commit();
					return {
						success: true,
						avatarUrl: event.fileID
					}
				}
			}
		} catch (e) {
			await transaction.rollback(-100)
			return {
				success: false,
				error: `rollback`,
				rollbackCode: -100,
			}
		}

	} else if (event.type == "doChange") {
		if (!event.newPwd) {
			//修改用户名
			let checkName = await db.collection("roomcenteruser").where({
				name: event.newname
			}).get();
			if (checkName.affectedDocs > 0) {
				return {
					success: 'fail',
					code: 5210
				}
			} else {
				let checkPwd = await db.collection("roomcenteruser").where({
					_id: event.uid,
					pwd: event.pwd
				}).get();
				//console.log(checkPwd);
				if (checkPwd.affectedDocs == 1) {
					return await db.collection("roomcenteruser").where({
						_id: event.uid
					}).update({
						name: event.newname
					});
				} else {
					return {
						success: 'fail',
						code: 'nopwd'
					}
				}

			}
		} else {
			let checkPwd = await db.collection("roomcenteruser").where({
				_id: event.uid,
				pwd: event.pwd
			}).get();
			if (checkPwd.affectedDocs == 1) {
				//修改密码
				return await db.collection("roomcenteruser").where({
					_id: event.uid
				}).update({
					pwd: event.newPwd
				});
			} else {
				return {
					success: 'fail',
					code: 'nopwd'
				}
			}

		}
	}

};